#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
移动端应用开发系统 (Mobile App Development System)

主要功能：
1. 移动端API接口开发
2. 实时数据推送服务
3. 离线数据同步机制
4. 移动端用户权限管理

作者: Assistant
日期: 2024
"""

import json
import csv
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any, Tuple
from enum import Enum
from dataclasses import dataclass, asdict
import uuid
import hashlib
import base64
from collections import defaultdict, deque
import threading
import time

class DeviceType(Enum):
    """设备类型"""
    IOS = "ios"
    ANDROID = "android"
    TABLET = "tablet"
    WEB_MOBILE = "web_mobile"

class NotificationType(Enum):
    """通知类型"""
    ALERT = "alert"
    INFO = "info"
    WARNING = "warning"
    CRITICAL = "critical"
    UPDATE = "update"

class SyncStatus(Enum):
    """同步状态"""
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"
    CONFLICT = "conflict"

class UserRole(Enum):
    """用户角色"""
    ADMIN = "admin"
    MANAGER = "manager"
    OPERATOR = "operator"
    VIEWER = "viewer"
    GUEST = "guest"

class APIEndpointType(Enum):
    """API端点类型"""
    INVENTORY = "inventory"
    ORDERS = "orders"
    SUPPLIERS = "suppliers"
    REPORTS = "reports"
    NOTIFICATIONS = "notifications"
    USER_MANAGEMENT = "user_management"
    ANALYTICS = "analytics"

@dataclass
class MobileUser:
    """移动端用户"""
    user_id: str
    username: str
    email: str
    role: str
    device_type: str
    device_id: str
    app_version: str
    last_login: datetime
    is_active: bool
    permissions: List[str]
    push_token: Optional[str] = None
    offline_data_limit: int = 1000  # MB
    
    def __post_init__(self):
        if self.last_login is None:
            self.last_login = datetime.now()

@dataclass
class APIEndpoint:
    """API端点配置"""
    endpoint_id: str
    path: str
    method: str  # GET, POST, PUT, DELETE
    endpoint_type: str
    description: str
    required_permissions: List[str]
    rate_limit: int  # requests per minute
    cache_duration: int  # seconds
    supports_offline: bool
    created_date: datetime
    is_active: bool = True
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class PushNotification:
    """推送通知"""
    notification_id: str
    user_id: str
    title: str
    message: str
    notification_type: str
    data: Dict[str, Any]
    scheduled_time: datetime
    sent_time: Optional[datetime]
    delivery_status: str
    priority: int  # 1-5, 5 is highest
    expires_at: datetime
    
    def __post_init__(self):
        if self.sent_time is None:
            self.sent_time = None
        if self.expires_at is None:
            self.expires_at = self.scheduled_time + timedelta(hours=24)

@dataclass
class OfflineData:
    """离线数据"""
    data_id: str
    user_id: str
    data_type: str
    data_content: Dict[str, Any]
    last_modified: datetime
    sync_status: str
    conflict_resolution: Optional[str]
    version: int
    size_mb: float
    
    def __post_init__(self):
        if self.last_modified is None:
            self.last_modified = datetime.now()

@dataclass
class SyncOperation:
    """同步操作"""
    sync_id: str
    user_id: str
    operation_type: str  # upload, download, conflict_resolution
    data_type: str
    status: str
    started_at: datetime
    completed_at: Optional[datetime]
    error_message: Optional[str]
    data_size: float
    progress_percentage: float
    
    def __post_init__(self):
        if self.started_at is None:
            self.started_at = datetime.now()
        if self.completed_at is None:
            self.completed_at = None

@dataclass
class APIUsageLog:
    """API使用日志"""
    log_id: str
    user_id: str
    endpoint_id: str
    method: str
    request_time: datetime
    response_time: datetime
    status_code: int
    response_size: int
    user_agent: str
    ip_address: str
    
    def __post_init__(self):
        if self.request_time is None:
            self.request_time = datetime.now()
        if self.response_time is None:
            self.response_time = datetime.now()

class MobileAppDevelopment:
    """移动端应用开发系统"""
    
    def __init__(self):
        self.mobile_users: Dict[str, MobileUser] = {}
        self.api_endpoints: Dict[str, APIEndpoint] = {}
        self.push_notifications: Dict[str, PushNotification] = {}
        self.offline_data: Dict[str, OfflineData] = {}
        self.sync_operations: Dict[str, SyncOperation] = {}
        self.api_usage_logs: List[APIUsageLog] = []
        
        # 实时推送相关
        self.active_connections: Dict[str, Any] = {}
        self.notification_queue: deque = deque()
        
        # 缓存和限流
        self.api_cache: Dict[str, Dict[str, Any]] = {}
        self.rate_limit_tracker: Dict[str, List[datetime]] = defaultdict(list)
        
        # 初始化默认API端点
        self._initialize_default_endpoints()
        
        # 启动后台服务
        self._start_background_services()
    
    def register_mobile_user(self, user_data: Dict[str, Any]) -> Optional[str]:
        """注册移动端用户"""
        try:
            user_id = f"MU_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            mobile_user = MobileUser(
                user_id=user_id,
                username=user_data['username'],
                email=user_data['email'],
                role=user_data.get('role', UserRole.VIEWER.value),
                device_type=user_data['device_type'],
                device_id=user_data['device_id'],
                app_version=user_data.get('app_version', '1.0.0'),
                last_login=datetime.now(),
                is_active=True,
                permissions=self._get_role_permissions(user_data.get('role', UserRole.VIEWER.value)),
                push_token=user_data.get('push_token'),
                offline_data_limit=user_data.get('offline_data_limit', 1000)
            )
            
            self.mobile_users[user_id] = mobile_user
            return user_id
            
        except Exception as e:
            print(f"注册移动端用户失败: {e}")
            return None
    
    def authenticate_user(self, username: str, password: str, device_id: str) -> Dict[str, Any]:
        """用户认证"""
        try:
            # 查找用户
            user = None
            for mobile_user in self.mobile_users.values():
                if mobile_user.username == username and mobile_user.device_id == device_id:
                    user = mobile_user
                    break
            
            if not user:
                return {'success': False, 'error': '用户不存在或设备不匹配'}
            
            if not user.is_active:
                return {'success': False, 'error': '用户账户已被禁用'}
            
            # 简化的密码验证（实际应用中应使用安全的哈希验证）
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            
            # 生成访问令牌
            access_token = self._generate_access_token(user.user_id)
            refresh_token = self._generate_refresh_token(user.user_id)
            
            # 更新最后登录时间
            user.last_login = datetime.now()
            
            return {
                'success': True,
                'user_id': user.user_id,
                'access_token': access_token,
                'refresh_token': refresh_token,
                'expires_in': 3600,  # 1小时
                'user_info': {
                    'username': user.username,
                    'email': user.email,
                    'role': user.role,
                    'permissions': user.permissions,
                    'device_type': user.device_type
                }
            }
            
        except Exception as e:
            print(f"用户认证失败: {e}")
            return {'success': False, 'error': '认证过程出现错误'}
    
    def create_api_endpoint(self, endpoint_data: Dict[str, Any]) -> Optional[str]:
        """创建API端点"""
        try:
            endpoint_id = f"EP_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            endpoint = APIEndpoint(
                endpoint_id=endpoint_id,
                path=endpoint_data['path'],
                method=endpoint_data['method'],
                endpoint_type=endpoint_data['endpoint_type'],
                description=endpoint_data.get('description', ''),
                required_permissions=endpoint_data.get('required_permissions', []),
                rate_limit=endpoint_data.get('rate_limit', 60),
                cache_duration=endpoint_data.get('cache_duration', 300),
                supports_offline=endpoint_data.get('supports_offline', False),
                created_date=datetime.now()
            )
            
            self.api_endpoints[endpoint_id] = endpoint
            return endpoint_id
            
        except Exception as e:
            print(f"创建API端点失败: {e}")
            return None
    
    def handle_api_request(self, user_id: str, endpoint_path: str, method: str, 
                          request_data: Dict[str, Any] = None) -> Dict[str, Any]:
        """处理API请求"""
        try:
            # 查找用户
            if user_id not in self.mobile_users:
                return {'status': 401, 'error': '用户未认证'}
            
            user = self.mobile_users[user_id]
            
            # 查找端点
            endpoint = None
            for ep in self.api_endpoints.values():
                if ep.path == endpoint_path and ep.method == method and ep.is_active:
                    endpoint = ep
                    break
            
            if not endpoint:
                return {'status': 404, 'error': 'API端点不存在'}
            
            # 检查权限
            if not self._check_permissions(user, endpoint.required_permissions):
                return {'status': 403, 'error': '权限不足'}
            
            # 检查速率限制
            if not self._check_rate_limit(user_id, endpoint):
                return {'status': 429, 'error': '请求过于频繁'}
            
            # 检查缓存
            cache_key = f"{user_id}_{endpoint_path}_{method}"
            cached_response = self._get_cached_response(cache_key, endpoint.cache_duration)
            if cached_response:
                return cached_response
            
            # 处理请求
            response = self._process_api_request(endpoint, request_data, user)
            
            # 缓存响应
            if response.get('status', 500) == 200 and endpoint.cache_duration > 0:
                self._cache_response(cache_key, response)
            
            # 记录API使用日志
            self._log_api_usage(user_id, endpoint.endpoint_id, method, response.get('status', 500))
            
            return response
            
        except Exception as e:
            print(f"处理API请求失败: {e}")
            return {'status': 500, 'error': '服务器内部错误'}
    
    def send_push_notification(self, notification_data: Dict[str, Any]) -> Optional[str]:
        """发送推送通知"""
        try:
            notification_id = f"PN_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            notification = PushNotification(
                notification_id=notification_id,
                user_id=notification_data['user_id'],
                title=notification_data['title'],
                message=notification_data['message'],
                notification_type=notification_data.get('notification_type', NotificationType.INFO.value),
                data=notification_data.get('data', {}),
                scheduled_time=notification_data.get('scheduled_time', datetime.now()),
                delivery_status='pending',
                priority=notification_data.get('priority', 3),
                expires_at=notification_data.get('expires_at')
            )
            
            self.push_notifications[notification_id] = notification
            
            # 如果是立即发送，加入队列
            if notification.scheduled_time <= datetime.now():
                self.notification_queue.append(notification_id)
            
            return notification_id
            
        except Exception as e:
            print(f"发送推送通知失败: {e}")
            return None
    
    def sync_offline_data(self, user_id: str, sync_data: Dict[str, Any]) -> Dict[str, Any]:
        """同步离线数据"""
        try:
            if user_id not in self.mobile_users:
                return {'success': False, 'error': '用户不存在'}
            
            sync_id = f"SYNC_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            # 创建同步操作记录
            sync_operation = SyncOperation(
                sync_id=sync_id,
                user_id=user_id,
                operation_type=sync_data.get('operation_type', 'upload'),
                data_type=sync_data.get('data_type', 'general'),
                status=SyncStatus.IN_PROGRESS.value,
                started_at=datetime.now(),
                data_size=sync_data.get('data_size', 0),
                progress_percentage=0
            )
            
            self.sync_operations[sync_id] = sync_operation
            
            # 处理同步数据
            sync_result = self._process_sync_operation(sync_operation, sync_data)
            
            # 更新同步状态
            sync_operation.status = sync_result['status']
            sync_operation.completed_at = datetime.now()
            sync_operation.progress_percentage = 100
            
            if sync_result['status'] == SyncStatus.FAILED.value:
                sync_operation.error_message = sync_result.get('error', '未知错误')
            
            return {
                'success': sync_result['status'] == SyncStatus.COMPLETED.value,
                'sync_id': sync_id,
                'status': sync_result['status'],
                'conflicts': sync_result.get('conflicts', []),
                'synced_items': sync_result.get('synced_items', 0),
                'message': sync_result.get('message', '')
            }
            
        except Exception as e:
            print(f"同步离线数据失败: {e}")
            return {'success': False, 'error': str(e)}
    
    def get_user_offline_data(self, user_id: str, data_type: str = None) -> Dict[str, Any]:
        """获取用户离线数据"""
        try:
            if user_id not in self.mobile_users:
                return {'error': '用户不存在'}
            
            user_offline_data = []
            total_size = 0
            
            for data in self.offline_data.values():
                if data.user_id == user_id:
                    if data_type is None or data.data_type == data_type:
                        user_offline_data.append({
                            'data_id': data.data_id,
                            'data_type': data.data_type,
                            'last_modified': data.last_modified,
                            'sync_status': data.sync_status,
                            'version': data.version,
                            'size_mb': data.size_mb,
                            'content': data.data_content
                        })
                        total_size += data.size_mb
            
            user = self.mobile_users[user_id]
            
            return {
                'user_id': user_id,
                'data_items': user_offline_data,
                'total_items': len(user_offline_data),
                'total_size_mb': total_size,
                'data_limit_mb': user.offline_data_limit,
                'usage_percentage': (total_size / user.offline_data_limit) * 100 if user.offline_data_limit > 0 else 0
            }
            
        except Exception as e:
            print(f"获取用户离线数据失败: {e}")
            return {'error': str(e)}
    
    def get_real_time_updates(self, user_id: str, last_update_time: datetime = None) -> Dict[str, Any]:
        """获取实时更新"""
        try:
            if user_id not in self.mobile_users:
                return {'error': '用户不存在'}
            
            user = self.mobile_users[user_id]
            updates = []
            
            # 获取未读通知
            unread_notifications = []
            for notification in self.push_notifications.values():
                if (notification.user_id == user_id and 
                    notification.delivery_status == 'pending' and
                    notification.scheduled_time <= datetime.now() and
                    notification.expires_at > datetime.now()):
                    
                    unread_notifications.append({
                        'notification_id': notification.notification_id,
                        'title': notification.title,
                        'message': notification.message,
                        'type': notification.notification_type,
                        'data': notification.data,
                        'priority': notification.priority,
                        'scheduled_time': notification.scheduled_time
                    })
            
            # 获取数据更新
            data_updates = self._get_data_updates(user_id, last_update_time)
            
            # 获取同步状态更新
            sync_updates = self._get_sync_updates(user_id, last_update_time)
            
            return {
                'user_id': user_id,
                'timestamp': datetime.now(),
                'notifications': unread_notifications,
                'data_updates': data_updates,
                'sync_updates': sync_updates,
                'total_updates': len(unread_notifications) + len(data_updates) + len(sync_updates)
            }
            
        except Exception as e:
            print(f"获取实时更新失败: {e}")
            return {'error': str(e)}
    
    def get_mobile_analytics(self, user_id: str = None) -> Dict[str, Any]:
        """获取移动端分析数据"""
        try:
            # 用户统计
            total_users = len(self.mobile_users)
            active_users = len([u for u in self.mobile_users.values() if u.is_active])
            
            # 设备类型分布
            device_distribution = {}
            for user in self.mobile_users.values():
                device_type = user.device_type
                device_distribution[device_type] = device_distribution.get(device_type, 0) + 1
            
            # API使用统计
            api_stats = self._calculate_api_usage_stats(user_id)
            
            # 推送通知统计
            notification_stats = self._calculate_notification_stats(user_id)
            
            # 同步统计
            sync_stats = self._calculate_sync_stats(user_id)
            
            # 离线数据统计
            offline_data_stats = self._calculate_offline_data_stats(user_id)
            
            analytics_data = {
                'overview': {
                    'total_users': total_users,
                    'active_users': active_users,
                    'total_api_endpoints': len(self.api_endpoints),
                    'total_notifications': len(self.push_notifications),
                    'total_sync_operations': len(self.sync_operations)
                },
                'device_distribution': device_distribution,
                'api_usage': api_stats,
                'notifications': notification_stats,
                'sync_operations': sync_stats,
                'offline_data': offline_data_stats,
                'generated_at': datetime.now()
            }
            
            if user_id:
                # 添加用户特定数据
                user_specific_data = self._get_user_specific_analytics(user_id)
                analytics_data['user_specific'] = user_specific_data
            
            return analytics_data
            
        except Exception as e:
            print(f"获取移动端分析数据失败: {e}")
            return {'error': str(e)}
    
    def export_mobile_data(self, file_path: str, data_type: str = "users") -> bool:
        """导出移动端数据"""
        try:
            if data_type == "users":
                data = [asdict(user) for user in self.mobile_users.values()]
            elif data_type == "api_endpoints":
                data = [asdict(endpoint) for endpoint in self.api_endpoints.values()]
            elif data_type == "notifications":
                data = [asdict(notification) for notification in self.push_notifications.values()]
            elif data_type == "sync_operations":
                data = [asdict(sync_op) for sync_op in self.sync_operations.values()]
            elif data_type == "offline_data":
                data = [asdict(offline) for offline in self.offline_data.values()]
            elif data_type == "api_logs":
                data = [asdict(log) for log in self.api_usage_logs]
            else:
                return False
            
            if not data:
                return False
            
            # 导出为CSV格式
            with open(file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
                if data:
                    # 处理嵌套字典和列表
                    processed_data = []
                    for row in data:
                        processed_row = {}
                        for key, value in row.items():
                            if isinstance(value, datetime):
                                processed_row[key] = value.strftime('%Y-%m-%d %H:%M:%S')
                            elif isinstance(value, (list, dict)):
                                processed_row[key] = json.dumps(value, ensure_ascii=False)
                            else:
                                processed_row[key] = value
                        processed_data.append(processed_row)
                    
                    fieldnames = processed_data[0].keys()
                    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                    writer.writeheader()
                    writer.writerows(processed_data)
            
            return True
            
        except Exception as e:
            print(f"导出移动端数据失败: {e}")
            return False
    
    # 私有辅助方法
    def _initialize_default_endpoints(self):
        """初始化默认API端点"""
        default_endpoints = [
            {
                'path': '/api/mobile/inventory',
                'method': 'GET',
                'endpoint_type': APIEndpointType.INVENTORY.value,
                'description': '获取库存信息',
                'required_permissions': ['inventory:read'],
                'supports_offline': True
            },
            {
                'path': '/api/mobile/orders',
                'method': 'GET',
                'endpoint_type': APIEndpointType.ORDERS.value,
                'description': '获取订单信息',
                'required_permissions': ['orders:read'],
                'supports_offline': True
            },
            {
                'path': '/api/mobile/suppliers',
                'method': 'GET',
                'endpoint_type': APIEndpointType.SUPPLIERS.value,
                'description': '获取供应商信息',
                'required_permissions': ['suppliers:read'],
                'supports_offline': False
            },
            {
                'path': '/api/mobile/reports',
                'method': 'GET',
                'endpoint_type': APIEndpointType.REPORTS.value,
                'description': '获取报告数据',
                'required_permissions': ['reports:read'],
                'supports_offline': False
            },
            {
                'path': '/api/mobile/notifications',
                'method': 'GET',
                'endpoint_type': APIEndpointType.NOTIFICATIONS.value,
                'description': '获取通知信息',
                'required_permissions': ['notifications:read'],
                'supports_offline': False
            }
        ]
        
        for endpoint_data in default_endpoints:
            self.create_api_endpoint(endpoint_data)
    
    def _get_role_permissions(self, role: str) -> List[str]:
        """获取角色权限"""
        role_permissions = {
            UserRole.ADMIN.value: [
                'inventory:read', 'inventory:write', 'inventory:delete',
                'orders:read', 'orders:write', 'orders:delete',
                'suppliers:read', 'suppliers:write', 'suppliers:delete',
                'reports:read', 'reports:write',
                'notifications:read', 'notifications:write',
                'users:read', 'users:write', 'users:delete',
                'analytics:read'
            ],
            UserRole.MANAGER.value: [
                'inventory:read', 'inventory:write',
                'orders:read', 'orders:write',
                'suppliers:read', 'suppliers:write',
                'reports:read',
                'notifications:read',
                'analytics:read'
            ],
            UserRole.OPERATOR.value: [
                'inventory:read', 'inventory:write',
                'orders:read', 'orders:write',
                'notifications:read'
            ],
            UserRole.VIEWER.value: [
                'inventory:read',
                'orders:read',
                'suppliers:read',
                'reports:read',
                'notifications:read'
            ],
            UserRole.GUEST.value: [
                'inventory:read',
                'notifications:read'
            ]
        }
        
        return role_permissions.get(role, [])
    
    def _generate_access_token(self, user_id: str) -> str:
        """生成访问令牌"""
        # 简化的令牌生成（实际应用中应使用JWT等标准）
        token_data = f"{user_id}:{datetime.now().timestamp()}"
        token_hash = hashlib.sha256(token_data.encode()).hexdigest()
        return base64.b64encode(token_hash.encode()).decode()
    
    def _generate_refresh_token(self, user_id: str) -> str:
        """生成刷新令牌"""
        # 简化的刷新令牌生成
        token_data = f"refresh:{user_id}:{datetime.now().timestamp()}"
        token_hash = hashlib.sha256(token_data.encode()).hexdigest()
        return base64.b64encode(token_hash.encode()).decode()
    
    def _check_permissions(self, user: MobileUser, required_permissions: List[str]) -> bool:
        """检查用户权限"""
        if not required_permissions:
            return True
        
        user_permissions = set(user.permissions)
        required_permissions_set = set(required_permissions)
        
        return required_permissions_set.issubset(user_permissions)
    
    def _check_rate_limit(self, user_id: str, endpoint: APIEndpoint) -> bool:
        """检查速率限制"""
        current_time = datetime.now()
        minute_ago = current_time - timedelta(minutes=1)
        
        # 清理过期的请求记录
        key = f"{user_id}_{endpoint.endpoint_id}"
        self.rate_limit_tracker[key] = [
            req_time for req_time in self.rate_limit_tracker[key]
            if req_time > minute_ago
        ]
        
        # 检查是否超过限制
        if len(self.rate_limit_tracker[key]) >= endpoint.rate_limit:
            return False
        
        # 记录当前请求
        self.rate_limit_tracker[key].append(current_time)
        return True
    
    def _get_cached_response(self, cache_key: str, cache_duration: int) -> Optional[Dict[str, Any]]:
        """获取缓存响应"""
        if cache_key in self.api_cache:
            cached_data = self.api_cache[cache_key]
            cache_time = cached_data.get('timestamp')
            
            if cache_time and (datetime.now() - cache_time).seconds < cache_duration:
                return cached_data.get('response')
        
        return None
    
    def _cache_response(self, cache_key: str, response: Dict[str, Any]):
        """缓存响应"""
        self.api_cache[cache_key] = {
            'timestamp': datetime.now(),
            'response': response
        }
    
    def _process_api_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理API请求"""
        # 模拟API请求处理
        if endpoint.endpoint_type == APIEndpointType.INVENTORY.value:
            return self._handle_inventory_request(endpoint, request_data, user)
        elif endpoint.endpoint_type == APIEndpointType.ORDERS.value:
            return self._handle_orders_request(endpoint, request_data, user)
        elif endpoint.endpoint_type == APIEndpointType.SUPPLIERS.value:
            return self._handle_suppliers_request(endpoint, request_data, user)
        elif endpoint.endpoint_type == APIEndpointType.REPORTS.value:
            return self._handle_reports_request(endpoint, request_data, user)
        elif endpoint.endpoint_type == APIEndpointType.NOTIFICATIONS.value:
            return self._handle_notifications_request(endpoint, request_data, user)
        else:
            return {'status': 200, 'data': {'message': 'API请求处理成功'}, 'timestamp': datetime.now()}
    
    def _handle_inventory_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理库存API请求"""
        # 模拟库存数据
        inventory_data = [
            {
                'item_id': 'ITEM001',
                'name': '产品A',
                'category': '电子产品',
                'current_stock': 150,
                'min_stock': 50,
                'max_stock': 500,
                'unit_price': 299.99,
                'location': '仓库A-01',
                'last_updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            },
            {
                'item_id': 'ITEM002',
                'name': '产品B',
                'category': '办公用品',
                'current_stock': 75,
                'min_stock': 30,
                'max_stock': 200,
                'unit_price': 45.50,
                'location': '仓库B-05',
                'last_updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        ]
        
        return {
            'status': 200,
            'data': {
                'items': inventory_data,
                'total_items': len(inventory_data),
                'low_stock_alerts': 1
            },
            'timestamp': datetime.now()
        }
    
    def _handle_orders_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理订单API请求"""
        # 模拟订单数据
        orders_data = [
            {
                'order_id': 'ORD001',
                'customer_name': '客户A',
                'order_date': '2024-01-15',
                'status': 'processing',
                'total_amount': 1299.99,
                'items_count': 3,
                'delivery_date': '2024-01-20'
            },
            {
                'order_id': 'ORD002',
                'customer_name': '客户B',
                'order_date': '2024-01-16',
                'status': 'shipped',
                'total_amount': 599.50,
                'items_count': 2,
                'delivery_date': '2024-01-18'
            }
        ]
        
        return {
            'status': 200,
            'data': {
                'orders': orders_data,
                'total_orders': len(orders_data),
                'pending_orders': 1
            },
            'timestamp': datetime.now()
        }
    
    def _handle_suppliers_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理供应商API请求"""
        # 模拟供应商数据
        suppliers_data = [
            {
                'supplier_id': 'SUP001',
                'name': '供应商A',
                'contact_person': '张经理',
                'phone': '138-0000-0001',
                'email': 'zhang@suppliera.com',
                'rating': 4.5,
                'status': 'active'
            },
            {
                'supplier_id': 'SUP002',
                'name': '供应商B',
                'contact_person': '李经理',
                'phone': '138-0000-0002',
                'email': 'li@supplierb.com',
                'rating': 4.2,
                'status': 'active'
            }
        ]
        
        return {
            'status': 200,
            'data': {
                'suppliers': suppliers_data,
                'total_suppliers': len(suppliers_data),
                'active_suppliers': 2
            },
            'timestamp': datetime.now()
        }
    
    def _handle_reports_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理报告API请求"""
        # 模拟报告数据
        reports_data = {
            'daily_summary': {
                'date': datetime.now().strftime('%Y-%m-%d'),
                'total_sales': 15678.90,
                'orders_processed': 45,
                'inventory_alerts': 3,
                'supplier_issues': 1
            },
            'kpi_metrics': {
                'inventory_turnover': 6.2,
                'order_fulfillment_rate': 0.96,
                'customer_satisfaction': 4.3,
                'supplier_performance': 0.89
            }
        }
        
        return {
            'status': 200,
            'data': reports_data,
            'timestamp': datetime.now()
        }
    
    def _handle_notifications_request(self, endpoint: APIEndpoint, request_data: Dict[str, Any], user: MobileUser) -> Dict[str, Any]:
        """处理通知API请求"""
        # 获取用户通知
        user_notifications = []
        for notification in self.push_notifications.values():
            if notification.user_id == user.user_id:
                user_notifications.append({
                    'notification_id': notification.notification_id,
                    'title': notification.title,
                    'message': notification.message,
                    'type': notification.notification_type,
                    'priority': notification.priority,
                    'scheduled_time': notification.scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'delivery_status': notification.delivery_status
                })
        
        return {
            'status': 200,
            'data': {
                'notifications': user_notifications,
                'total_notifications': len(user_notifications),
                'unread_count': len([n for n in user_notifications if n['delivery_status'] == 'pending'])
            },
            'timestamp': datetime.now()
        }
    
    def _log_api_usage(self, user_id: str, endpoint_id: str, method: str, status_code: int):
        """记录API使用日志"""
        log_id = f"LOG_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
        
        api_log = APIUsageLog(
            log_id=log_id,
            user_id=user_id,
            endpoint_id=endpoint_id,
            method=method,
            request_time=datetime.now(),
            response_time=datetime.now(),
            status_code=status_code,
            response_size=1024,  # 模拟响应大小
            user_agent='MobileApp/1.0',
            ip_address='192.168.1.100'
        )
        
        self.api_usage_logs.append(api_log)
        
        # 保持日志数量在合理范围内
        if len(self.api_usage_logs) > 10000:
            self.api_usage_logs = self.api_usage_logs[-5000:]
    
    def _process_sync_operation(self, sync_operation: SyncOperation, sync_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理同步操作"""
        try:
            operation_type = sync_operation.operation_type
            
            if operation_type == 'upload':
                return self._process_upload_sync(sync_operation, sync_data)
            elif operation_type == 'download':
                return self._process_download_sync(sync_operation, sync_data)
            elif operation_type == 'conflict_resolution':
                return self._process_conflict_resolution(sync_operation, sync_data)
            else:
                return {'status': SyncStatus.FAILED.value, 'error': '不支持的同步操作类型'}
                
        except Exception as e:
            return {'status': SyncStatus.FAILED.value, 'error': str(e)}
    
    def _process_upload_sync(self, sync_operation: SyncOperation, sync_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理上传同步"""
        try:
            upload_items = sync_data.get('items', [])
            synced_items = 0
            conflicts = []
            
            for item in upload_items:
                data_id = item.get('data_id')
                
                # 检查是否存在冲突
                existing_data = self.offline_data.get(data_id)
                if existing_data and existing_data.version != item.get('version', 1):
                    conflicts.append({
                        'data_id': data_id,
                        'conflict_type': 'version_mismatch',
                        'server_version': existing_data.version,
                        'client_version': item.get('version', 1)
                    })
                    continue
                
                # 创建或更新离线数据
                offline_data = OfflineData(
                    data_id=data_id or f"DATA_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}",
                    user_id=sync_operation.user_id,
                    data_type=item.get('data_type', 'general'),
                    data_content=item.get('content', {}),
                    last_modified=datetime.now(),
                    sync_status=SyncStatus.COMPLETED.value,
                    version=item.get('version', 1) + 1,
                    size_mb=item.get('size_mb', 0.1)
                )
                
                self.offline_data[offline_data.data_id] = offline_data
                synced_items += 1
            
            if conflicts:
                return {
                    'status': SyncStatus.CONFLICT.value,
                    'synced_items': synced_items,
                    'conflicts': conflicts,
                    'message': f'同步完成，但存在{len(conflicts)}个冲突需要解决'
                }
            else:
                return {
                    'status': SyncStatus.COMPLETED.value,
                    'synced_items': synced_items,
                    'message': f'成功同步{synced_items}个项目'
                }
                
        except Exception as e:
            return {'status': SyncStatus.FAILED.value, 'error': str(e)}
    
    def _process_download_sync(self, sync_operation: SyncOperation, sync_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理下载同步"""
        try:
            # 获取用户的离线数据
            user_data = self.get_user_offline_data(sync_operation.user_id, sync_data.get('data_type'))
            
            if 'error' in user_data:
                return {'status': SyncStatus.FAILED.value, 'error': user_data['error']}
            
            return {
                'status': SyncStatus.COMPLETED.value,
                'synced_items': user_data['total_items'],
                'data': user_data['data_items'],
                'message': f'成功下载{user_data["total_items"]}个项目'
            }
            
        except Exception as e:
            return {'status': SyncStatus.FAILED.value, 'error': str(e)}
    
    def _process_conflict_resolution(self, sync_operation: SyncOperation, sync_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理冲突解决"""
        try:
            resolutions = sync_data.get('resolutions', [])
            resolved_items = 0
            
            for resolution in resolutions:
                data_id = resolution.get('data_id')
                resolution_strategy = resolution.get('strategy')  # 'use_server', 'use_client', 'merge'
                
                if data_id in self.offline_data:
                    offline_data = self.offline_data[data_id]
                    
                    if resolution_strategy == 'use_server':
                        # 保持服务器版本
                        offline_data.sync_status = SyncStatus.COMPLETED.value
                    elif resolution_strategy == 'use_client':
                        # 使用客户端版本
                        offline_data.data_content = resolution.get('client_data', {})
                        offline_data.version += 1
                        offline_data.last_modified = datetime.now()
                        offline_data.sync_status = SyncStatus.COMPLETED.value
                    elif resolution_strategy == 'merge':
                        # 合并数据
                        merged_data = {**offline_data.data_content, **resolution.get('merged_data', {})}
                        offline_data.data_content = merged_data
                        offline_data.version += 1
                        offline_data.last_modified = datetime.now()
                        offline_data.sync_status = SyncStatus.COMPLETED.value
                    
                    resolved_items += 1
            
            return {
                'status': SyncStatus.COMPLETED.value,
                'synced_items': resolved_items,
                'message': f'成功解决{resolved_items}个冲突'
            }
            
        except Exception as e:
            return {'status': SyncStatus.FAILED.value, 'error': str(e)}
    
    def _get_data_updates(self, user_id: str, last_update_time: datetime = None) -> List[Dict[str, Any]]:
        """获取数据更新"""
        updates = []
        
        # 模拟数据更新
        if last_update_time is None:
            last_update_time = datetime.now() - timedelta(hours=1)
        
        # 检查离线数据更新
        for data in self.offline_data.values():
            if (data.user_id == user_id and 
                data.last_modified > last_update_time):
                
                updates.append({
                    'type': 'data_update',
                    'data_id': data.data_id,
                    'data_type': data.data_type,
                    'last_modified': data.last_modified,
                    'sync_status': data.sync_status
                })
        
        return updates
    
    def _get_sync_updates(self, user_id: str, last_update_time: datetime = None) -> List[Dict[str, Any]]:
        """获取同步更新"""
        updates = []
        
        if last_update_time is None:
            last_update_time = datetime.now() - timedelta(hours=1)
        
        # 检查同步操作更新
        for sync_op in self.sync_operations.values():
            if (sync_op.user_id == user_id and 
                sync_op.started_at > last_update_time):
                
                updates.append({
                    'type': 'sync_update',
                    'sync_id': sync_op.sync_id,
                    'operation_type': sync_op.operation_type,
                    'status': sync_op.status,
                    'progress_percentage': sync_op.progress_percentage,
                    'started_at': sync_op.started_at,
                    'completed_at': sync_op.completed_at
                })
        
        return updates
    
    def _calculate_api_usage_stats(self, user_id: str = None) -> Dict[str, Any]:
        """计算API使用统计"""
        logs = self.api_usage_logs
        if user_id:
            logs = [log for log in logs if log.user_id == user_id]
        
        if not logs:
            return {'total_requests': 0, 'success_rate': 0, 'avg_response_time': 0}
        
        total_requests = len(logs)
        successful_requests = len([log for log in logs if 200 <= log.status_code < 300])
        success_rate = (successful_requests / total_requests) * 100 if total_requests > 0 else 0
        
        # 模拟平均响应时间
        avg_response_time = 150  # ms
        
        # 按端点统计
        endpoint_stats = {}
        for log in logs:
            endpoint_id = log.endpoint_id
            if endpoint_id not in endpoint_stats:
                endpoint_stats[endpoint_id] = {'requests': 0, 'errors': 0}
            
            endpoint_stats[endpoint_id]['requests'] += 1
            if log.status_code >= 400:
                endpoint_stats[endpoint_id]['errors'] += 1
        
        return {
            'total_requests': total_requests,
            'successful_requests': successful_requests,
            'success_rate': success_rate,
            'avg_response_time_ms': avg_response_time,
            'endpoint_stats': endpoint_stats
        }
    
    def _calculate_notification_stats(self, user_id: str = None) -> Dict[str, Any]:
        """计算通知统计"""
        notifications = list(self.push_notifications.values())
        if user_id:
            notifications = [n for n in notifications if n.user_id == user_id]
        
        if not notifications:
            return {'total_notifications': 0, 'delivery_rate': 0}
        
        total_notifications = len(notifications)
        delivered_notifications = len([n for n in notifications if n.delivery_status == 'delivered'])
        delivery_rate = (delivered_notifications / total_notifications) * 100 if total_notifications > 0 else 0
        
        # 按类型统计
        type_stats = {}
        for notification in notifications:
            ntype = notification.notification_type
            type_stats[ntype] = type_stats.get(ntype, 0) + 1
        
        return {
            'total_notifications': total_notifications,
            'delivered_notifications': delivered_notifications,
            'delivery_rate': delivery_rate,
            'type_distribution': type_stats
        }
    
    def _calculate_sync_stats(self, user_id: str = None) -> Dict[str, Any]:
        """计算同步统计"""
        sync_ops = list(self.sync_operations.values())
        if user_id:
            sync_ops = [s for s in sync_ops if s.user_id == user_id]
        
        if not sync_ops:
            return {'total_syncs': 0, 'success_rate': 0}
        
        total_syncs = len(sync_ops)
        successful_syncs = len([s for s in sync_ops if s.status == SyncStatus.COMPLETED.value])
        success_rate = (successful_syncs / total_syncs) * 100 if total_syncs > 0 else 0
        
        # 按操作类型统计
        operation_stats = {}
        for sync_op in sync_ops:
            op_type = sync_op.operation_type
            operation_stats[op_type] = operation_stats.get(op_type, 0) + 1
        
        return {
            'total_syncs': total_syncs,
            'successful_syncs': successful_syncs,
            'success_rate': success_rate,
            'operation_distribution': operation_stats
        }
    
    def _calculate_offline_data_stats(self, user_id: str = None) -> Dict[str, Any]:
        """计算离线数据统计"""
        offline_data_list = list(self.offline_data.values())
        if user_id:
            offline_data_list = [d for d in offline_data_list if d.user_id == user_id]
        
        if not offline_data_list:
            return {'total_items': 0, 'total_size_mb': 0}
        
        total_items = len(offline_data_list)
        total_size = sum(data.size_mb for data in offline_data_list)
        
        # 按数据类型统计
        type_stats = {}
        for data in offline_data_list:
            dtype = data.data_type
            if dtype not in type_stats:
                type_stats[dtype] = {'count': 0, 'size_mb': 0}
            
            type_stats[dtype]['count'] += 1
            type_stats[dtype]['size_mb'] += data.size_mb
        
        return {
            'total_items': total_items,
            'total_size_mb': total_size,
            'type_distribution': type_stats
        }
    
    def _get_user_specific_analytics(self, user_id: str) -> Dict[str, Any]:
        """获取用户特定分析数据"""
        if user_id not in self.mobile_users:
            return {}
        
        user = self.mobile_users[user_id]
        
        # 用户活动统计
        user_logs = [log for log in self.api_usage_logs if log.user_id == user_id]
        last_activity = max([log.request_time for log in user_logs]) if user_logs else user.last_login
        
        # 用户离线数据使用情况
        offline_data_info = self.get_user_offline_data(user_id)
        
        return {
            'user_info': {
                'user_id': user_id,
                'username': user.username,
                'role': user.role,
                'device_type': user.device_type,
                'app_version': user.app_version,
                'last_login': user.last_login,
                'last_activity': last_activity
            },
            'activity_stats': {
                'total_api_calls': len(user_logs),
                'avg_daily_calls': len(user_logs) / 30 if user_logs else 0  # 假设30天内的数据
            },
            'offline_data_usage': offline_data_info
        }
    
    def _start_background_services(self):
        """启动后台服务"""
        # 启动通知处理线程
        notification_thread = threading.Thread(target=self._process_notification_queue, daemon=True)
        notification_thread.start()
        
        # 启动缓存清理线程
        cache_cleanup_thread = threading.Thread(target=self._cleanup_cache, daemon=True)
        cache_cleanup_thread.start()
    
    def _process_notification_queue(self):
        """处理通知队列"""
        while True:
            try:
                if self.notification_queue:
                    notification_id = self.notification_queue.popleft()
                    if notification_id in self.push_notifications:
                        notification = self.push_notifications[notification_id]
                        
                        # 模拟发送通知
                        notification.sent_time = datetime.now()
                        notification.delivery_status = 'delivered'
                        
                        print(f"通知已发送: {notification.title} -> {notification.user_id}")
                
                time.sleep(1)  # 每秒检查一次
                
            except Exception as e:
                print(f"处理通知队列错误: {e}")
                time.sleep(5)
    
    def _cleanup_cache(self):
        """清理过期缓存"""
        while True:
            try:
                current_time = datetime.now()
                expired_keys = []
                
                for cache_key, cache_data in self.api_cache.items():
                    cache_time = cache_data.get('timestamp')
                    if cache_time and (current_time - cache_time).seconds > 3600:  # 1小时过期
                        expired_keys.append(cache_key)
                
                for key in expired_keys:
                    del self.api_cache[key]
                
                if expired_keys:
                    print(f"清理了{len(expired_keys)}个过期缓存")
                
                time.sleep(300)  # 每5分钟清理一次
                
            except Exception as e:
                print(f"清理缓存错误: {e}")
                time.sleep(600)  # 出错时等待10分钟